package com.smartstate.dataManagement.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.db.sql.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartstate.dataManagement.dto.PageDTO;
import com.smartstate.dataManagement.entity.Permission;


import com.smartstate.dataManagement.entity.User;
import com.smartstate.dataManagement.eunm.CommonEunm;
import com.smartstate.dataManagement.mapper.PermissionMapper;
import com.smartstate.dataManagement.mapper.RoleMapper;
import com.smartstate.dataManagement.mapper.UserMapper;
import com.smartstate.dataManagement.service.PermissionService;
import com.smartstate.dataManagement.util.DateTimeUtil;
import com.smartstate.dataManagement.util.StringUtils;
import com.smartstate.dataManagement.util.UserUtils;
import com.smartstate.dataManagement.util.WrapperUtil;
import com.smartstate.dataManagement.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.security.BasicPermission;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

@Service
@Slf4j
public class PermissionImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    HttpServletRequest  request;


    @Override
    public Page<Permission> queryAllPageByDTO(PageDTO pageDTO) {
        return null;
    }

    @Override
    public List<Permission> findAll() {
        return permissionMapper.findAll();
    }

    @Override
    public ResultVO<List<Permission>> getPerByRoleID(String roleID) {
        // 根据权限ID获取权限列表
        List<Permission> permissionList = new ArrayList<>();
        // 判断是否存在该角色
        if(null!=roleMapper.getByRoleId(roleID)) {
            // 根据角色ID获取权限ID集合数据
            List<String> permId = permissionMapper.getPerIdByRoleId(roleID);
            if (permId.size()>0) {
                permissionList = permissionMapper.getPermsList(permId);
                return ResultVO.ok(permissionList);
            }
            return ResultVO.ok(permissionList);
        }
        return ResultVO.fail("该角色不存在");
    }

    @Override
    public Page<Permission> getPermByNameAndStatus(String name,String status,PageDTO<Permission> pageDTO) {
        Page<Permission> page =new Page<>(pageDTO.getPage(),pageDTO.getSize());
        QueryWrapper<Permission> wrapper = WrapperUtil.convertQuery(pageDTO.getDto(),Permission.class);
        wrapper.orderByDesc(CommonEunm.CREATETIME.getValue());
        // 根据账户和状态进行查询 ， 否则列表数据
        if(StringUtils.isNotBlank(name) ||  StringUtils.isNotBlank(status)){
            // 判断该用户是否存在,
            List<String> userId=userMapper.getUserByUserame(name,status);
            if(userId.size()>0){
                // 获取该用户的角色
                List<String> roleId=userMapper.getRoleByUserId(userId);
                // 根据角色ID获取权限集合
                if(roleId.size()>0){
                    List<String> permIds = permissionMapper.getPermIdsByRoleId(roleId);
                    // 根据权限ID获取权限数据
                    if(permIds.size()>0) {
                        wrapper.in(CommonEunm.ID.getValue(), permIds);
                    }
                    else{
                        wrapper.in(CommonEunm.ID.getValue(), "");
                    }
                    return baseMapper.selectPage(page,wrapper);
                }
            }
        }
        else{//   默认查询
            baseMapper.selectPage(page,wrapper);
        }
        return  page;
    }

    @Override
    public ResultVO<Permission> addChildOrFather(Permission permission) {
        if(null != permission){
            // 获取用户的信息
            User user=userMapper.getUser(UserUtils.getLoginUser().getId());
            if(StringUtils.isNotBlank(permission.getParentId()) && StringUtils.isNotBlank(permission.getName())){
                permission.setId(IdUtil.randomUUID());
                Permission temp=null;
                // 菜单不可重名
//                Permission demo=permissionMapper.getPerm(permission.getName());
//                if(null ==demo){
                    permission.setId(IdUtil.objectId());
                    permission.setCreateTime(new Date());
                    permission.setState(CommonEunm.STATUS_ON.getValue());
                    permission.setComponent(permission.getComponent());
                    permission.setUrlPath(permission.getUrlPath());
                    permission.setSort(permission.getSort());
                    permission.setCreateUser(user.getNickname());
                    if(permissionMapper.addChild(permission)>0){
                        return ResultVO.ok(permission,"新增成功");
                    }
                    return  ResultVO.fail("新增失败");
//                }
//               return ResultVO.fail("该菜单名已经存在,不能重复添加");
            }
            return  ResultVO.fail("缺失必要参数， 请输入参数");
        }
        return  ResultVO.fail("参数为空， 请输入参数");
    }

    @Override
    public Boolean updateByPermID(Permission permission) {
        Boolean result=false;
        // 获取当前用户
        User user =userMapper.getUser(UserUtils.getLoginUser().getId());
        permission.setUpdateUser(user.getNickname());
        permission.setUpdateTime(new Date());
        if(permissionMapper.updateByPermID(permission)>0){
            result=true;
        }
        return result;
    }

    @Override
    public Boolean delByID(String id) {
        Boolean result=false;
        if(permissionMapper.deleteById(id)>0){
            result=true;
        }
        return result;
    }

    @Override
    public Boolean updateStatuByID(String id, String status) {
        Boolean result=false;
        // 获取当前登录的用户
        User user =userMapper.getUser(UserUtils.getLoginUser().getId());
        if(permissionMapper.updateStatuByID(id,status,user.getNickname(),DateTimeUtil.localDateTime2String(LocalDateTime.now()))>0){
            result=true;
        }
        return result;
    }

    @Override
    public Boolean delBatchByIDs(List<String> ids) {
        Boolean result=false;
        if(permissionMapper.delBatchByIDs(ids)>0){
            result=true;
        }
        return result;
    }

    @Override
    public List<Permission> lazyLoadMeun(String id) {
        return permissionMapper.lazyLoadMeun(id);
    }

    @Override
    public ResultVO<List<Permission>> loadAllMeun() {
        List<Permission> permissionAllList=new ArrayList<>();
        // 先获取顶级菜单
        List<Permission>  list=permissionMapper.getListByParentId(CommonEunm.ZERO.getValue());
        // 获取全部的菜单List
        List<Permission>  noBaseList=permissionMapper.getNoBaseList();
        // 遍历
        for(Permission permission:list){
            List<Permission> menus = iterateMenus(noBaseList,permission.getId());
            permission.setList(menus);
        }
        // 调用数据组装
//        addData(permissionAllList,list);
        return ResultVO.ok(list);
    }

    @Override
    public List<Permission> findPermissionByUserId(String id) {
        return permissionMapper.findPermissionByUserId(id);
    }


    public List<Permission> iterateMenus(List<Permission> menuVoList,String pid){
        List<Permission> result = new ArrayList<Permission>();
        for (Permission menu : menuVoList) {
            //获取菜单的id
            String menuid = menu.getId();
            //获取菜单的父id
            String parentid = menu.getParentId();
            if(StringUtils.isNotBlank(parentid)){
                if(parentid.equals(pid)){
                    //递归查询当前子菜单的子菜单
                    List<Permission> iterateMenu = iterateMenus(menuVoList,menuid);
                    menu.setList(iterateMenu);
                    result.add(menu);
                }
            }
        }
        return result;
    }



    /**
     *    获取子级菜单
      */
    public List<Permission>  getAll(Permission permission){
        return  permissionMapper.getListByParentId(permission.getId());
    }

}
